#!/bin/bash

# 应用名称
APP_NAME="caregiver-watch"
# jar包名称
JAR_NAME="caregiver-watch-0.0.1.jar"
# JVM参数
JVM_OPTS="-Xms512m -Xmx1024m -XX:+UseG1GC"
# 应用端口
SERVER_PORT=8001
# 日志目录
LOG_PATH="./logs"
# PID文件
PID_FILE="./$APP_NAME.pid"

# 创建日志目录
mkdir -p $LOG_PATH

# 使用说明
usage() {
    echo "Usage: $0 {start|stop|restart|status}"
    exit 1
}

# 启动应用
start() {
    # 检查应用是否已经运行
    if [ -f "$PID_FILE" ]; then
        PID=$(cat $PID_FILE)
        if ps -p $PID > /dev/null 2>&1; then
            echo "$APP_NAME is already running. PID: $PID"
            return 1
        else
            # PID文件存在但进程不存在，删除PID文件
            rm -f $PID_FILE
        fi
    fi

    echo "Starting $APP_NAME..."

    # 后台启动应用
    nohup java $JVM_OPTS \
        -jar $JAR_NAME \
        --spring.profiles.active=test \
        --server.port=$SERVER_PORT \
        --logging.file.path=$LOG_PATH \
        > $LOG_PATH/startup.log 2>&1 &

    # 保存PID
    echo $! > $PID_FILE

    # 等待几秒检查是否启动成功
    sleep 5

    # 检查启动状态
    if ps -p $(cat $PID_FILE) > /dev/null 2>&1; then
        echo "$APP_NAME started successfully. PID: $(cat $PID_FILE)"
    else
        echo "Failed to start $APP_NAME"
        rm -f $PID_FILE
        return 1
    fi
}

# 停止应用
stop() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat $PID_FILE)
        if ps -p $PID > /dev/null 2>&1; then
            echo "Stopping $APP_NAME..."
            kill $PID

            # 等待应用停止
            TIMEOUT=30
            while [ $TIMEOUT -gt 0 ] && ps -p $PID > /dev/null 2>&1; do
                sleep 1
                TIMEOUT=$((TIMEOUT - 1))
            done

            if ps -p $PID > /dev/null 2>&1; then
                echo "Force killing $APP_NAME..."
                kill -9 $PID
            fi

            rm -f $PID_FILE
            echo "$APP_NAME stopped."
        else
            echo "$APP_NAME is not running."
            rm -f $PID_FILE
        fi
    else
        echo "$APP_NAME is not running."
    fi
}

# 查看应用状态
status() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat $PID_FILE)
        if ps -p $PID > /dev/null 2>&1; then
            echo "$APP_NAME is running. PID: $PID"
        else
            echo "$APP_NAME is not running but PID file exists."
            rm -f $PID_FILE
        fi
    else
        echo "$APP_NAME is not running."
    fi
}

# 重启应用
restart() {
    stop
    sleep 2
    start
}

# 根据参数执行相应操作
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    *)
        usage
        ;;
esac

exit 0
